package com._54programer;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IndexTest2 {

    public static void main(String[] args) throws Exception {
        //配置集群名称，注意采用的事情TCP接口调用
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //配置请求地址和端口
        InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300);
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(address);
        //* 1.获取客户端
        //* 2.创建mapping请求对象:需要设置index,type,请求体
        PutMappingRequestBuilder request = client.admin().indices().preparePutMapping("blog1");
        request.setType("article");//设置type
        //* 3.创建JSON请求体:参考第一天的设置Mapping的JSON数据
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
        jsonBuilder.startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id").field("type","long").field("store","yes").field("index","not_analyzed")
                .endObject()
                .startObject("title").field("type","string").field("store","yes").field("index","analyzed").field("analyzer","ik_smart")
                .endObject()
                .startObject("content").field("type","string").field("store","yes").field("index","analyzed").field("analyzer","ik_smart")
                .endObject()
                .endObject()
                .endObject()
                .endObject();
        request.setSource(jsonBuilder);//设置请求体
        //* 4.请求对象执行发送请求操作,请求完成会获取响应对象
        PutMappingResponse response = request.get();
        System.out.println(response.toString());
        //* 5.关闭客户端
        client.close();

    }

}
